#include "SockStream.h"
#include "SockAcceptor.h"

#include <errno.h>
#include <stdio.h>
#include <sys/epoll.h>
#include <iostream>

int main ()
{
    InetAddr local_addr (9999);

    SockStream peer;
    SockAcceptor acceptor;
    if (acceptor.open (local_addr) != 0)
    {
        std::cout << errno << std::endl;
        perror ("open");
        return 0;
    }
    InetAddr remote_addr;
    if (acceptor.accept (peer, &remote_addr) != 0)
    {
        std::cout << errno << std::endl;
        perror ("accept");
        return 0;
    }
    NDK::set_non_block_mode (peer.handle ());
    char buff[512] = {0};
    int ep_fd = epoll_create (20);
    struct epoll_event ep, evs[20];
    ep.events  = EPOLLIN | EPOLLOUT | EPOLLET;
    ep.data.fd = peer.handle ();
    epoll_ctl (ep_fd, EPOLL_CTL_ADD, peer.handle (), &ep);

    char sendstr[1024*1024] = {'x'};
    int i = 0;
    while (i++ < 400000000)
    {
        int ret = epoll_wait (ep_fd, evs, 20, -1);
        if (ret <= 0)
        {
            perror ("select");
            std::cout << "timeout of error, ret = " << ret << std::endl;
        }
        if (i == 1)
        {
            //peer.recv (buff, 2);
            ret = peer.send (sendstr, sizeof(sendstr));
            std::cout 
                << "we don't recv data at the first time! send ret = " 
                << ret 
                <<  std::endl;
            continue;
        }
        std::cout << "wait recv " << std::endl;
        while(1)
        {
            ret = peer.recv (buff, 512);
            std::cout << buff << "ret = " << ret << std::endl;
            if (ret <= 0)
                break;
        }
        std::cout << buff << "ret = " << ret << std::endl;
        peer.send (buff, ret);
    }
    peer.close ();
    return 0;
}
